//
//  BaseTabBarView.m
//  MoodDiary
//
//  Created by MoodDiary on 2020/11/26.
//

#import "BaseTabBarView.h"

#import "TabBarButton.h"
#import "BaseTabBarButton.h"
#import "SpecialTabBarButton.h"

@interface BaseTabBarView ()

@property (weak, nonatomic) UIButton *selectButton;

@end

@implementation BaseTabBarView

static NSInteger const kTagPlus = 1000000;

- (RACSubject *)subject {
    if (!_subject) {
        _subject = [RACSubject subject];
    }
    return _subject;
}

- (instancetype)init {
    if (self = [super init]) {
        self.backgroundColor = [UIColor whiteColor];
    }
    return self;
}

- (void)setTabBarItemsArray:(NSMutableArray *)tabBarItemsArray {
    _tabBarItemsArray = tabBarItemsArray;
    
    for (int i = 0; i < tabBarItemsArray.count; i ++) {
        TabBarButton *btn;
        if (i == 2) {
            btn = [SpecialTabBarButton buttonWithType:0];
        } else {
            btn = [BaseTabBarButton buttonWithType:0];
        }
        btn.tabBarItem = tabBarItemsArray[i];
        btn.tag = kTagPlus + i;
        if (i == 0) {
            btn.selected = YES;
            self.selectButton = btn;
        }
        [self addSubview:btn];
    }
}

- (void)layoutSubviews {
    CGFloat btnWidth = DEF_SCREEN_WIDTH / _tabBarItemsArray.count;
    CGFloat btnHeight = self.height;
    for (int i = 0; i < _tabBarItemsArray.count; i ++) {
        BaseTabBarButton *btn = [self viewWithTag:kTagPlus + i];
        btn.frame = CGRectMake(btnWidth * i, 0, btnWidth, btnHeight);
        [btn addTarget:self action:@selector(btnClick:) forControlEvents:UIControlEventTouchDown];
    }
}

- (void)btnClick:(UIButton *)selectedBtn {
    if (self.selectButton == selectedBtn) {
        selectedBtn.selected = YES;
    } else if (selectedBtn.tag - kTagPlus != 2) {
        selectedBtn.selected = YES;
        self.selectButton.selected = NO;
        self.selectButton = selectedBtn;
    }
    [self.subject sendNext:[NSString stringWithFormat:@"%ld",selectedBtn.tag - kTagPlus]];
}

@end
